# Copyright (c) 2012 Nathan Grubb
# Available under the new BSD license; see LICENSE.txt

"""plugin/operator.py: Comprehensive implementation of operator-level commands."""

class Operator(object):
    type = "command"
    permissions = "op"
    name = "operator"
    desc = "Plugin implementing operator commands"
    commands = {"kick": 1, "voice": 1, "devoice": 1, "op": 1, "deop": 1, 
                "invite": 1, "topic": 1, "ban": 1, "unban": 1,}

    def __init__(self, api, msg):
        self.api = api
        self.msg = msg

    def set_mode(self, mode, args):
        """Reusable function to apply a mode to all users (args).
        """

        channel = self.msg.args[0]     
        nicks = args
        
        for nick in nicks:
            self.api.grubbot.connection.send("mode", channel, mode, nick)

    def command_kick(self, args):
        channel = self.msg.args[0]
        nick = args[0]
        reason = None

        if len(args) > 1:
            reason = " ".join(args[1:])

        if reason:
            self.api.grubbot.connection.send("kick", channel, nick, reason)
        else:
            self.api.grubbot.connection.send("kick", channel, nick)

    def command_ban(self, args):
        self.set_mode("+b", args)

    def command_unban(self, args):
        self.set_mode("-b", args)

    def command_voice(self, args):
        self.set_mode("+v", args)

    def command_devoice(self, args):
        self.set_mode("-v", args)

    def command_op(self, args):
        self.set_mode("+o", args)

    def command_deop(self, args):
        self.set_mode("-o", args)

    def command_invite(self, args):
        nicks = args
        for nick in nicks:
            self.api.grubbot.connection.send("invite", nick, self.msg.args[0])

    def command_topic(self, args):
        channel = self.msg.args[0]
        topic = " ".join(args)
        self.api.grubbot.connection.send("topic", channel, topic)

plugin = Operator